<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>课程表系统 - 登录</title>
    <link href="/css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv">
    <form id="loginForm">
        <h1>登录界面</h1>
        <div id="errorMsg" style="color:red; display:none;"></div>
        <p><label for="username">用户名:</label><input id="username" name="username" type="text" required></p>
        <p><label for="password"> 密码: </label><input id="password" name="password" type="password" required></p>
        <p>
            <label for="captcha">验证码:</label>
            <input id="captcha" name="captcha" type="text" required maxlength="4" style="width: 100px;">
            <!-- 使用登录专用验证码路径 -->
            <img id="captchaImg" src="/kaptcha/login.jpg" alt="验证码"
                 onclick="this.src='/kaptcha/login.jpg?'+Math.random()"
                 style="vertical-align: middle; cursor: pointer;">
            <span style="font-size: 12px; color: #666;">点击图片刷新</span>
        </p>
        <p>
            <input type="checkbox" id="remember" name="remember">
            <label for="remember">记住账号</label>
        </p>
        <div>
            <button type="submit" class="button">登录</button>
            <button type="button" class="button" onclick="register()">注册</button>
            <button type="reset" class="button">重置</button>
        </div>
    </form>
</div>

<script src="js/axios.min.js"></script>
<script>
    // 页面加载时检查 Cookie 并填充用户名
    window.onload = function() {
        const username = getCookie('rememberedUsername');
        if (username) {
            document.getElementById('username').value = username;
            document.getElementById('remember').checked = true;
        }
    };

    // 表单提交处理（登录）
    document.getElementById('loginForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const captcha = document.getElementById('captcha').value;
        const remember = document.getElementById('remember').checked;

        // 前端简单验证
        if (!captcha || captcha.trim().length !== 4) {
            showError('请输入4位验证码');
            return;
        }

        axios.post('/loginServlet', {
            username: username,
            password: password,
            captcha: captcha,   //传递验证码
            remember: remember  // 传递记住我选项
        })
            .then(response => {
                if (response.data.success) {
                    alert('登录成功！');
                    window.location.href = 'home.html';
                } else {
                    // 只有验证码错误时才刷新验证码
                    if (response.data.message === "验证码错误") {
                        refreshCaptcha('login');
                    }
                    showError(response.data.message);
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                showError('网络错误，请重试');
            });
    });

    // 注册函数
    function register() {
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const captcha = document.getElementById('captcha').value;

        if (!username || !password) {
            showError('请先填写账号和密码');
            return;
        }

        if (!captcha || captcha.trim().length !== 4) {
            showError('请输入4位验证码');
            return;
        }

        if (!confirm('确认注册账号: ' + username + '?')) {
            return;
        }

        axios.post('/registerServlet', {
            username: username,
            password: password,
            captcha: captcha
        })
            .then(response => {
                if (response.data.success) {
                    alert('注册成功！请登录');
                    document.getElementById('password').value = '';
                    // 注册成功后不需要刷新验证码（用户会跳转到登录页）
                } else {
                    // 只有验证码错误时才刷新验证码
                    if (response.data.message === "验证码错误") {
                        refreshCaptcha('register');
                    }
                    showError(response.data.message);
                }
            })
            .catch(error => {
                console.error('注册失败:', error);
                showError('注册失败，请重试');
            });
    }

    // 刷新验证码（支持登录/注册两种类型）
    function refreshCaptcha(type) {
        const captchaUrl = type === 'register' ? '/kaptcha/register.jpg' : '/kaptcha/login.jpg';
        document.getElementById('captchaImg').src = captchaUrl + '?' + Math.random();
        document.getElementById('captcha').value = '';
    }

    // 显示错误信息
    function showError(message) {
        const errorMsg = document.getElementById('errorMsg');
        errorMsg.textContent = message;
        errorMsg.style.display = 'block';

        // 点击输入框隐藏错误
        document.getElementById('username').onclick = () => errorMsg.style.display = 'none';
        document.getElementById('password').onclick = () => errorMsg.style.display = 'none';
    }

    // Cookie 操作函数
    function setCookie(name, value, days) {
        const expires = new Date();
        expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = name + '=' + encodeURIComponent(value) + ';expires=' + expires.toUTCString() + ';path=/';
    }

    function getCookie(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for(let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
        }
        return null;
    }

    // 清除 Cookie
    function deleteCookie(name) {
        document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;';
    }
</script>
</body>
</html>